package com.xbh.management.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nimbusds.jose.JOSEException;
import com.xbh.common.utils.RedisUtils;
import com.xbh.common.web.core.Result;
import com.xbh.file.api.FileTransferFeignClient;
import com.xbh.management.annotation.Authorization;
import com.xbh.management.api.CaptchaFeignService;
import com.xbh.management.entity.ManUserVO;
import com.xbh.management.exception.JwtSignatureVerifyException;
import com.xbh.management.model.ManMenu;
import com.xbh.management.model.ManUser;
import com.xbh.management.service.UserService;
import com.xbh.management.utils.JwtUtilManagement;
import com.xbh.management.utils.TreeNodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @program: management-center
 * @description:
 * @author: 许宝华
 * @create: 2021-08-29 19:35
 */
@RestController
@RequestMapping(path = "/user")

public class UserController {
    private static Logger log = LoggerFactory.getLogger(UserController.class);



    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private CaptchaFeignService captchaFeignService;

    @Autowired
    private FileTransferFeignClient fileTransferFeignClient;
    /**
     * 分页查询所有用户，支持username模糊查询
     * @param params
     * @return
     */
    @PostMapping("/page")
    public Result page(@RequestBody JSONObject params){
        Long pageNum = params.getLong("pageNum");
        Long pageSize = params.getLong("pageSize");

        ManUser manUser = params.toJavaObject(ManUser.class);
        IPage<ManUser> userIPage = userService.queryAllUser(new Page<ManUser>(pageNum, pageSize), manUser);
        return Result.success(userIPage);

    }

    /**
     * 保存用户
     * @param params
     * @return
     * @throws ParseException
     * @throws JwtSignatureVerifyException
     * @throws JOSEException
     */
    @PostMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public Result saveUser(@RequestBody JSONObject params) throws ParseException, JwtSignatureVerifyException, JOSEException {
        ManUser manUser = params.toJavaObject(ManUser.class);
        manUser.setCreatePerson(JwtUtilManagement.getUsername());
        manUser.setUpdatePerson(JwtUtilManagement.getUsername());
        int isFlag = userService.saveUser(manUser);
        if(isFlag>0){
            return Result.success(isFlag);
        }
        return Result.failed("保存失败");
    }

    /**
     * 根据userId查询用户
     * @param parmas
     * @return
     */
    @PostMapping("/selectUserId")
    public Result queryUserWithUserId(@RequestBody JSONObject parmas){
        Long userId = parmas.getLong("userId");
        ManUser user = userService.queryUserWithUserId(userId);
        return Result.success(user);

    }

    /**
     * 根据id修改用户信息
     * @param params
     * @return
     */
    @PostMapping("/updateUserId")
    public Result updateUserWithUserId(@RequestBody JSONObject params){
        ManUser manUser = params.toJavaObject(ManUser.class);
        int isFlag = userService.updateUserWithUserId(manUser);
        if(isFlag>0){
            return Result.success(isFlag);
        }
        return Result.failed("修改失败");
    }


    /**
     * 根据id修改密码
      * @param params
     * @return
     */
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody JSONObject params){
        ManUser manUser = params.toJavaObject(ManUser.class);
        int isFlag = userService.updatePasswordWithUserId(manUser);
        if(isFlag>0){
            return Result.success(isFlag);
        }
        return Result.failed("修改失败");
    }

    /**
     * 导出用户
     * @param params
     * @return
     */
    @PostMapping("/exportUser")
    public Result exportUser(@RequestBody JSONObject params) throws Exception {
        Integer pageNum = params.getInteger("pageNum");
        Integer pageSize = params.getInteger("pageSize");

        ManUser user = params.toJavaObject(ManUser.class);

        //导出当前页数据
        IPage<ManUser> list = userService.queryAllUser(new Page<ManUser>(pageNum, pageSize), user);
        List<ManUser> records = list.getRecords();
        String downloadURL= userService.exportUser(records);

        return Result.result("000","获取地址成功",downloadURL);
    }

    /**
     * 查询当前用户所拥有的的角色
     * @param params
     * @return
     */
    @PostMapping("/selectUserRelationAllRole")
    public Result queryUserRelationAllRole(@RequestBody JSONObject params){
        ManUser user = params.toJavaObject(ManUser.class);
        ManUserVO manUserVO = userService.queryUserRelationAllRole(user);
        if(manUserVO==null){
            return Result.failed("004","没有数据");
        }
        return Result.success(manUserVO);
    }
    /**
     * 查询当前用户所拥有的的菜单
     * @param params
     * @return
     */
    @PostMapping("/selectUserRelationAllMenuBy")
    public Result queryUserRelationAllMenuBy(@RequestBody JSONObject params){
        ManUser user = params.toJavaObject(ManUser.class);
        ManUserVO manUserVO = userService.queryUserRelationAllMenu(user);
        if(manUserVO == null){
            return Result.failedParams("当前用户还没有关联菜单");
        }
        List<ManMenu> menuList = manUserVO.getMenuList();
        List<ManMenu> manMenus = TreeNodeUtil.transformData(menuList, "0");
        if(manUserVO==null){
            return Result.failed("004","没有数据");
        }
        return Result.success(manMenus);
    }
    /**
     * 查询当前用户所拥有的的菜单
     * @param params
     * @return
     */
    @PostMapping("/selectUserRelationAllMenu")
    public Result queryUserRelationAllMenu(@RequestBody JSONObject params){
        ManUser user = params.toJavaObject(ManUser.class);
        ManUserVO manUserVO = userService.queryUserRelationAllMenu(user);
        if(manUserVO == null){
            return Result.failedParams("当前用户还没有关联菜单");
        }
        List<ManMenu> menuList = manUserVO.getMenuList();
        List<ManMenu> manMenus = TreeNodeUtil.transformData(menuList, "119853844214895");
        if(manUserVO==null){
            return Result.failed("004","没有数据");
        }
        return Result.success(manMenus);
    }
    /**
     * 生成验证码
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/code")
    public Result saveCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String code = captchaFeignService.captchaPng(request, response);
        return Result.success(code);
    }


    /**
     * 修改头像
     *
     * @param file
     * @param req
     * @return
     */
//    @Authorization
    @PostMapping("/uploader")
    public Result uploader(@RequestParam("file") MultipartFile file) throws ParseException, JOSEException, JwtSignatureVerifyException {


        Result result = fileTransferFeignClient.uploadPicture(file);
        HashMap data = (HashMap) result.getData();
        String url = data.get("fileUrl").toString();

        String username = JwtUtilManagement.getUsername();

        //生成新的URL的同时更新该用户数据库的地址值
        int isFlag = userService.updateUserWithUsername(username, url);

        if (isFlag > 0) {
            return Result.success(url);
        }
        return Result.failed("修改头像失败");
    }

    /**
     * 获取头像
     * @param params
     * @return
     */
    @Authorization
    @PostMapping("/getImage")
    public Result getImage(@RequestBody JSONObject params) {
        String username = params.getString("username");
        String imageURL = userService.queryUserWithUsername(username);
        return Result.success(imageURL);
    }

    /**
     * 根据用户名称返回用户信息
     * @param params
     * @return
     */
    @PostMapping("/queryUserByUsername")
    public Result queryUserByUsername(@RequestBody JSONObject params) {
        String username = params.getString("username");
        List<ManUser> manUsers = userService.queryUserByUsername(username);
        if(CollectionUtil.isNotEmpty(manUsers)){
            List<JSONObject> userJson = new ArrayList<>();
            manUsers.stream().forEach( user ->{
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("username",user.getUsername());
                jsonObject.put("userId",user.getUserId());
                jsonObject.put("personName",user.getPersonName());
                userJson.add(jsonObject);

            });
            return Result.success(userJson);
        }
        return Result.success();
    }
}
